package com.example.dqdq.lzyim_asm_tvapp.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by DQDQ on 16/8/20.
 */
public class FileDownLoad {


    public String downLoadApk(String urlStr, Context context) {
        String path = "file";
        String fileName = "app-debug.apk";
        String pathName = "";
        OutputStream output = null;
        try {

            String SDCard = Environment.getExternalStorageDirectory() + "";
            pathName = SDCard + "/" + path + "/" + fileName;//文件存储路径
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            int length = conn.getContentLength();
            InputStream is = conn.getInputStream();

            File file = new File(SDCard + "/" + path);
            if (!file.exists()) {
                file.mkdir();
                System.err.println("创建savePath:" + SDCard + "/" + path);
            }
            String apkFile = pathName;
            File ApkFile = new File(apkFile);
            FileOutputStream fos = new FileOutputStream(ApkFile);

            int count = 0;
            byte buf[] = new byte[1024];

            do {
                int numread = is.read(buf);
                count += numread;
                if (numread <= 0) {
                    break;
                }
                fos.write(buf, 0, numread);
            } while (true);

            fos.close();
            is.close();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File apkfile = new File(pathName);
        if (!apkfile.exists()) {
            return "";
        }

        return apkfile.toString();
    }
}
